package com.e3.core.base;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

import com.e3.web.core.model.SuperModel;


@Transactional
public class SuperService extends AbstractSuperService{
	
	protected <T extends SuperEntity> T createEntity(Class<T> entityClass,long id){
		try {
			T entity = entityClass.newInstance();
			if(id>0){
				entity.setId(id);
			}
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	protected <T extends SuperEntity> T modelToEntity(Class<T> entityClass,SuperModel model,T entity){
		T tEntity = entity;
		long id = model.getId();
		if(tEntity == null){
			tEntity = createEntity(entityClass, id);
		}
		
		Long createTime = tEntity.getCreateTime();
		Date currentDate = new Date();
		if(createTime == null){
			model.setCreateTime(currentDate);
			tEntity.setCreateTime(currentDate.getTime());
		}
		
		Long userId = tEntity.getCreateUserId();
		if(userId == null){
			model.setCreateUserId(SessionContext.getUserID());
			tEntity.setCreateUserId(SessionContext.getUserID());
		}
		
		model.setModifyTime(currentDate);
		tEntity.setModifyTime(currentDate.getTime());
		
		model.setModifyUserId(SessionContext.getUserID());
		tEntity.setModifyUserId(SessionContext.getUserID());
		return tEntity;
	}
	
	protected <T extends SuperOCEntity> T ocModelToEntity(Class<T> entityClass,SuperModel model,T entity){
		T tEntity = modelToEntity(entityClass, model, entity);
		
		Long corpId = tEntity.getCorpId();
		if(corpId == null){
			tEntity.setCorpId(SessionContext.getCorpID());
		}
		
		return tEntity;
	}

}
